import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import S from '@/spx'
import { Provider } from 'react-redux'
import configStore from '@/store'
import api from '@/api'
import { SG_ROUTER_PARAMS, SG_GUIDE_PARAMS, SG_GUIDE_PARAMS_UPDATETIME } from '@/consts'
import {
  checkAppVersion,
  isWeixin,
  isWeb,
  isNavbar,
  log,
  entryLaunch,
  publicshare,
  isAPP,
  isWxWeb
} from '@/utils'
import { requestIntercept } from '@/plugin/requestIntercept'
import dayjs from 'dayjs'

import './app.scss'

// 如果需要在 h5 环境中开启 React Devtools
// 取消以下注释：
// if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5')  {
//   require('nerv-devtools')
// }

const { store } = configStore()

// 如果是app模式，注入SAPP
if (process.env.APP_BUILD_TARGET == 'app') {
  import('@/plugin/app/index').then(({ SAPP }) => {
    SAPP.init(Taro, store)
  })
} else {
  import('@/plugin/routeIntercept').then(({ intercept }) => {
    intercept.init()
  })
}

requestIntercept()

class App extends Component {
  // componentWillMount() {
  //   this.getSystemConfig()
  //   // if ( S.getAuthToken() ) {
  //   //   store.dispatch(fetchUserFavs());
  //   // }
  // }

  componentDidMount() {}

  async onLaunch(options) {}

  async componentDidShow(options) {
    if (isWeixin) {
      checkAppVersion()
    }
    // isWeb环境下，H5启动时，路由携带参数在options
    // 小程序环境，启动时，路由携带参数在options.query
    entryLaunch.getRouteParams(isWeb ? { query: options } : options).then((params) => {
      Taro.setStorageSync(SG_ROUTER_PARAMS, params)

      // 已缓存的导购参数
      const guideParams = Taro.getStorageSync(SG_GUIDE_PARAMS) || {}
      const guideUpdateTime = Taro.getStorageSync(SG_GUIDE_PARAMS_UPDATETIME) || ''
      const diffMilliseconds = dayjs().diff(dayjs(guideUpdateTime))
      // 参数保存超过3天，清除导购参数
      if (diffMilliseconds > 3 * 86400000) {
        Taro.removeStorageSync(SG_GUIDE_PARAMS)
        Taro.removeStorageSync(SG_GUIDE_PARAMS_UPDATETIME)
      } else {
        // 欢迎语携带用户编号
        if (guideParams?.gu_user_id) {
          delete guideParams.gu_user_id
        }
        Taro.setStorageSync(SG_GUIDE_PARAMS, {
          ...guideParams,
          ...params
        })
        Taro.setStorageSync(SG_GUIDE_PARAMS_UPDATETIME, dayjs().unix())
      }

      // 导购UV上报
      if (S.getAuthToken()) {
        entryLaunch.postGuideUV()
        entryLaunch.postGuideTask()
      }
    })
    const { show_time } = await api.promotion.getScreenAd()
    let showAdv
    if (show_time === 'always') {
      showAdv = false
      store.dispatch({
        type: 'user/closeAdv',
        payload: showAdv
      })
    }
    this.getSystemConfig()

    //绑定上下级
    if (isWeixin || isAPP()) {
      let { company_id, shareUserId, scene, q, dtUserId } = options.query || options
      let url = ''
      // app分享小程序
      if (scene) {
        let sceneObj = this.parseUrlStr(decodeURIComponent(scene))
        if (sceneObj.uid) {
          shareUserId = sceneObj.uid
        } else if (sceneObj.share_id && sceneObj.share_id.indexOf('-')) {
          shareUserId = sceneObj.share_id.slice(sceneObj.share_id.indexOf('-') + 1)
        }
      }
      const userinfo = await Taro.getStorageSync('userinfo')
      // 扫描普通二维码逻辑处理
      if (q) {
        const qUrl = decodeURIComponent(q)
        url = '/' + qUrl.split('/').slice(3).join('/')
        const qObj = this.parseUrlStr(qUrl)
        shareUserId = qObj.shareUserId
        if (qObj.dtUserId) shareUserId = qObj.dtUserId
        company_id = qObj.company_id
      }
      if (dtUserId) shareUserId = dtUserId
      // 保存分享人信息
      if (shareUserId && shareUserId != 'undefined') {
        Taro.setStorage({
          key: 'share',
          data: {
            time: Date.now(),
            company_id: company_id || 1,
            shareUserId: shareUserId
          },
          success: () => {
            publicshare(userinfo.userId)
          }
        })
      } else {
        publicshare(userinfo.userId)
      }
      if (url) {
        Taro.navigateTo({
          url: url
        })
      }
    }
  }
  // 格式化URL字符串
  parseUrlStr(str) {
    if ('string' != typeof str) return str
    if (str.indexOf('&') < 0 && str.indexOf('=') < 0) return {}
    let newStr = str.split('&'),
      newOjb = {}
    newStr.forEach((value) => {
      if (value.indexOf('=') > -1) {
        let newStr1 = value.split('=')
        newOjb[newStr1[0]] = newStr1[1]
      }
    })
    return newOjb
  }
  async getSystemConfig() {
    const {
      echat,
      meiqia,
      disk_driver = 'qiniu',
      whitelist_status = false,
      nostores_status = false,
      distributor_param_status = false,
      point_rule_name = '积分'
    } = await api.shop.homeSetting()

    const {
      tab_bar,
      is_open_recommend: openRecommend,
      is_open_scan_qrcode: openScanQrcode,
      is_open_wechatapp_location: openLocation,
      is_open_official_account: openOfficialAccount,
      color_style: { primary, accent, marketing },
      title // 商城应用名称
    } = await api.shop.getAppBaseInfo()

    const priceSetting = await api.shop.getAppGoodsPriceSetting()

    Taro.setStorageSync('distributor_param_status', distributor_param_status)

    try {
      const tabBar = JSON.parse(tab_bar)
      store.dispatch({
        type: 'sys/setSysConfig',
        payload: {
          initState: true,
          colorPrimary: primary,
          colorMarketing: marketing,
          colorAccent: accent,
          pointName: point_rule_name,
          tabbar: tabBar,
          openRecommend, // 开启猜你喜欢 1开启 2关闭
          openScanQrcode, // 开启扫码功能 1开启 2关闭
          openLocation, // 开启小程序定位 1开启 2关闭
          openOfficialAccount, // 开启关注公众号组件 1开启 2关闭
          diskDriver: disk_driver,
          appName: title,
          echat,
          meiqia,
          openStore: !nostores_status, // 前端店铺展示是否关闭 true:开启 false:关闭（接口返回值为true:关闭 false:不关闭）
          priceSetting
        }
      })
      // 兼容老的主题方式
      store.dispatch({
        type: 'colors/setColor',
        payload: {
          primary,
          marketing,
          accent
        }
      })
    } catch (error) {
    }
  }

  componentDidCatchError() {}

  render() {
    return <Provider store={store}>{this.props.children}</Provider>
  }
}

export default App
